package bamin.com.bamindaijia.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.app.SysApplication;
import com.aiton.administrator.shane_library.shane.utils.GetIpAddressUtil;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.HTTPUtils;
import com.aiton.administrator.shane_library.shane.utils.VolleyListener;
import com.aiton.administrator.shane_library.shane.widget.MyCarDialog;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.alipay.sdk.app.PayTask;
import com.android.volley.VolleyError;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import bamin.com.bamindaijia.R;
import bamin.com.bamindaijia.Zalipay.PayResult;
import bamin.com.bamindaijia.constant.Constant;
import bamin.com.bamindaijia.model.Order;
import bamin.com.bamindaijia.model.Sign;
import bamin.com.bamindaijia.model.WechatOrderInfo;
import cz.msebera.android.httpclient.Header;

import static bamin.com.bamindaijia.R.id.tv_comfirm_toll;


public class PayActivity extends ZjbBaseActivity implements View.OnClickListener {

    //    private Cost mCost;
    private Order mOrder;
    private TextView mTextView_start;
    private TextView mTextView_end;
    private TextView mTextView_time;
    private TextView mTextView_mileage;
    private TextView mTextView_cost;
    private TextView mTextView_mes;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;
    private String[] payModeStr = new String[]{"微信", "支付宝", "个人账户"};
    private String payMode;// 支付方式
    final IWXAPI api = WXAPIFactory.createWXAPI(this, null);
    private String WechatPay_APPID = "wx349c8646bb5f1809";
    private MyCarDialog myCarDialog;
    private Map<String, String> mGetWechatOrderParams;

    /**
     * 支付宝支付动作完成后的回调
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        //支付成功向金点通发送确认订单
                        paySucces();
//                        setDialog01("支付成功", "确认");
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            setFailDialog("支付结果确认中", "确认");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            setFailDialog("支付失败", "确认");
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(PayActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }
    };
    private RadioGroup pay_mode;
    private RadioButton radiobtn_pay_weixin;
    private RadioButton radiobtn_pay_zhifubao;
    private View mRela_pay_mes;
    private TextView mTextView_costorder_other_money;
    private TextView mTextView_comfirm_toll;
    private TextView mTextView_fee;
    private TextView mTextView_mileage_money;
    private TextView mTextView_order_waiting_time;
    private TextView mTextView_order_waiting_time_money;
    private Double mTollFees;
    private Double mOtherFees;

    /**
     * 支付成功
     */
    private void paySucces() {
//        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
//        //发透传给司机，弹出dialog
//        setSuccessDialog("支付成功", "确认");
        Intent intent = new Intent(PayActivity.this, PingJiaActivity.class);
//        intent.putExtra(Constant.INTENT_KEY.PINGJIA, Constant.INTENT_KEY.PAY);

        intent.putExtra(Constant.INTENT_KEY.ORDER, mOrder);


        startActivity(intent);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        api.registerApp(WechatPay_APPID);

        init();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initViews() {
        mTextView_start.setText(mOrder.getStartLocation());
        mTextView_end.setText(mOrder.getEndLocation());
        mTextView_time.setText("下单时间：" + mOrder.getOrderTime());
        mTextView_mileage.setText("里程(" + mOrder.getMileage() + "公里)");
        mTextView_cost.setText(mOrder.getSumMoney() + "");

        mTextView_mileage.setText("里程(" + mOrder.getMileage() + "公里)");
        mTextView_mileage_money.setText(mOrder.getMileageCost() + "元");

        mTextView_order_waiting_time.setText("等待费用(" + mOrder.getWaitTime() + "分钟)");
        mTextView_order_waiting_time_money.setText(mOrder.getWaitTimeFee() + "元");

        mTextView_fee.setText(mOrder.getFee() + "元");

        mTextView_comfirm_toll.setText(mOrder.getTollFees() + "元");

        mTextView_costorder_other_money.setText(mOrder.getOtherFees() + "元");

        mTollFees = mOrder.getTollFees();

        if (mTollFees == null) {
            mTollFees = 0d;
        }
        mOtherFees = mOrder.getOtherFees();
        if (mOtherFees == null) {
            mOtherFees = 0d;
        }
        if (mTollFees == 0 && mOtherFees == 0) {
            mRela_pay_mes.setVisibility(View.GONE);
        } else {
            mRela_pay_mes.setVisibility(View.VISIBLE);
            mTextView_mes.setText("路桥费：" + mTollFees + "元,其他费用：" + mOtherFees + "元");
        }
//        if (TextUtils.isEmpty(mCost.getMeassage())) {
//            mRela_pay_mes.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.button_pay).setOnClickListener(this);
        pay_mode.setOnCheckedChangeListener(new CheckListener());
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
//        mCost = (Cost) intent.getSerializableExtra(Constant.INTENT_KEY.COST);
        mOrder = (Order) intent.getSerializableExtra(Constant.INTENT_KEY.ORDER);

    }

    @Override
    protected void findID() {
        mTextView_start = (TextView) findViewById(R.id.textView_start);
        mTextView_end = (TextView) findViewById(R.id.textView_end);
        mTextView_time = (TextView) findViewById(R.id.textView_time);
        mTextView_mileage = (TextView) findViewById(R.id.tv_order_mileage);
        mTextView_mileage_money = (TextView) findViewById(R.id.tv_order_mileage_money);
        mTextView_order_waiting_time = (TextView) findViewById(R.id.tv_order_waiting_time);
        mTextView_order_waiting_time_money = (TextView) findViewById(R.id.tv_order_waiting_time_money);

        mTextView_cost = (TextView) findViewById(R.id.textView_price);
        mTextView_mes = (TextView) findViewById(R.id.textView_mes);
        mTextView_costorder_other_money = (TextView) findViewById(R.id.tv_order_other_money);
        mTextView_comfirm_toll = (TextView) findViewById(tv_comfirm_toll);
        mTextView_fee = (TextView) findViewById(R.id.textView_fee);


        mRela_pay_mes = findViewById(R.id.rela_pay_mes);
        pay_mode = (RadioGroup) findViewById(R.id.radio_pay_mode);
        radiobtn_pay_weixin = (RadioButton) findViewById(R.id.radiobtn_pay_weixin);
        radiobtn_pay_zhifubao = (RadioButton) findViewById(R.id.radiobtn_pay_zhifubao);

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    //支付失败dialog提示
    private void setFailDialog(String messageTxt, String iSeeTxt) {

        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, messageTxt, iSeeTxt);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();

            }
        });
        singleBtnDialog.show();
    }

    //支付成功dialog提示
    private void setSuccessDialog(String messageTxt, String iSeeTxt) {

        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, messageTxt, iSeeTxt);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();


            }
        });
        singleBtnDialog.show();
    }

    /**
     * 获取签名
     */
    private void getSign() {
        String url = Constant.Url.GETSIGN;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();

        params.put("out_trade_no", mOrder.getOrderId());
        params.put("subject", mOrder.getStartLocation() + "-" + mOrder.getEndLocation());
        // TODO: 2016/10/27
        double money = mOrder.getMileageCost() + mOrder.getFee() + mOrder.getWaitTimeFee();
        if (0 != mTollFees) {
            money += mTollFees;
        }
        if (0 != mOtherFees) {
            money += mOtherFees;
        }
        if (TextUtils.equals(mOrder.getCustomerPhone(), "18750690369")||TextUtils.equals(mOrder.getCustomerPhone(), "15871105320")) {
            money = 0.01;
        }
        params.put("total_fee", money + "");
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                try {
                    Sign sign = GsonUtils.parseJSON(s, Sign.class);
                    final String body = sign.getBody();
                    Log.e("onResponse", "返回值" + body);
                    Runnable payRunnable = new Runnable() {
                        @Override
                        public void run() {
                            // 构造PayTask 对象
                            PayTask alipay = new PayTask(PayActivity.this);
                            // 调用支付接口，获取支付结果
                            String result = alipay.pay(body, true);

                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };

                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                } catch (Exception e) {
                    setFailDialog( "数据出错", "确定");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_pay:
                getSign();

//                if (payModeStr[0].equals(payMode)) {
////                    wechatPay();
//                } else if (payModeStr[1].equals(payMode)) {
//                    getSign();
//
//                }
                break;
        }
    }

    class CheckListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (radiobtn_pay_weixin.isChecked()) {
                payMode = payModeStr[0];
            } else if (radiobtn_pay_zhifubao.isChecked()) {
                payMode = payModeStr[1];
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        SysApplication.getInstance().exit();
    }

    private void wechatPay() {
        if (!checkIsSupportedWeachatPay()) {
            Toast.makeText(this, "您暂未安装微信或您的微信版本暂不支持支付功能\n请下载安装最新版本的微信", Toast.LENGTH_SHORT).show();
        } else {
            wechatPayRequest();
        }
    }

    /**
     * 检查微信版本是否支付支付或是否安装可支付的微信版本
     */
    private boolean checkIsSupportedWeachatPay() {
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        return isPaySupported;
    }

    private void wechatPayRequest() {
        showLoadingDialog();
        setStructureParameters();
        getWechatPayOrderPrepayIdAndSign();
    }

    /**
     * 构建向服务端获取微信预支付订单的相关参数
     */
    private void setStructureParameters() {

        String outTradeNo = getOutTradeNo();
        mGetWechatOrderParams = new HashMap<String, String>();
        mGetWechatOrderParams.put("body", "");// 商品描述
        mGetWechatOrderParams.put("out_trade_no", outTradeNo);// 商户订单号
        mGetWechatOrderParams.put("total_fee", "");// 总金额
        mGetWechatOrderParams.put("spbill_create_ip", GetIpAddressUtil.getPhoneIp());// 终端IP
        mGetWechatOrderParams.put("trade_type", "APP");// 交易类型
    }

    /**
     * 微信支付:获取服务端的预支付订单及签名
     */
    private void getWechatPayOrderPrepayIdAndSign() {
        if (!myCarDialog.isShowing()) {
            myCarDialog.show();
        }
        // TODO: 2016/9/25
        HTTPUtils.post(this, "", mGetWechatOrderParams,
                new VolleyListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(PayActivity.this, "微信支付失败", Toast.LENGTH_SHORT).show();
                        myCarDialog.dismiss();
                    }

                    @Override
                    public void onResponse(String s) {
                        Log.e("weixin", "微信预支付返回值" + s);
                        myCarDialog.dismiss();
                        WechatOrderInfo wechatOrderInfo = GsonUtils.parseJSON(s, WechatOrderInfo.class);
                        SendWechatPay(wechatOrderInfo);
                    }
                });

    }

    /**
     * 微信支付:通过微信SDK发起微信支付请求
     */
    private void SendWechatPay(WechatOrderInfo wechatOrderInfo) {
        PayReq mPayReq = new PayReq();
        mPayReq.appId = wechatOrderInfo.getMap().getAppid();
        mPayReq.partnerId = wechatOrderInfo.getMap().getPartnerid();
        mPayReq.prepayId = wechatOrderInfo.getMap().getPrepayid();
        mPayReq.packageValue = wechatOrderInfo.getMap().getPackageX();
        mPayReq.nonceStr = wechatOrderInfo.getMap().getNoncestr();
        mPayReq.timeStamp = wechatOrderInfo.getMap().getTimestamp();
        mPayReq.sign = wechatOrderInfo.getSign();
        api.sendReq(mPayReq);
        Log.e("WechatPay ", "sendWechatPayForReq:" + "向微信发起支付请求");
        findViewById(R.id.pay).setEnabled(true);
    }

    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    private String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);
        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }
}
